package com.yjd.comm.web.session;

import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.yjd.comm.util.ServletUtil;

/**
 * A manager for the CSRF token for a given session. The
 * {@link #getTokenForSession(HttpSession)} should used to obtain the token
 * value for the current session (and this should be the only way to obtain the
 * token value).
 * ***/

public final class CSRFTokenManager {

	/**
	 * The token parameter name
	 */
	public static final String CSRF_PARAM_NAME = "_CSRFToken";

	/**
	 * The location on the session which stores the token
	 */
	public static final String CSRF_NAME = CSRFTokenManager.class.getName()
			+ ".tokenval";

	public static String getTokenForSession(HttpServletRequest request,
			HttpServletResponse response, Map<String, Object> sessionMap) {
		String token = null;

		token = (String) sessionMap.get(CSRF_NAME);
		if (null == token) {
			token = UUID.randomUUID().toString();
			ServletUtil.putSession(request, response, CSRF_NAME, token);
		}
		return token;
	}

	private CSRFTokenManager() {
	};

}